<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\BehaviorCategory;
use app\common\model\Category as CategoryModel;
use app\common\model\Config as ConfigModel;
use app\common\model\Config;
use app\common\model\Dorm;
use app\common\model\Semester;
use app\common\model\User;
use fast\Tree;

/**
 * 排行榜
 *
 */
class Ranking extends Backend
{
    protected $layout = 'default';

    /**
     * @var \app\common\model\Category
     */
    protected $model = null;
    protected $categorylist = [];
    protected $noNeedRight = ['*'];

    protected $typeData = [
        '1' => '今日',
        '2' => '昨天',
        '3' => '本周',
        '4' => '上周',
        '6' => '本月',
        '7' => '本学期'
    ];

    protected $config = [];

    public function _initialize()
    {
        if ($this->request->action() == 'show') {
            $this->layout = false;
        }

        parent::_initialize();

        $this->model = model('BehaviorRecord');

        $this->config = ConfigModel::getByName('ranking_setting');
        $this->view->assign('type', $this->config->value);

        $this->view->assign('typeData', $this->typeData);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {

            $type = $this->request->request('type', 1);


            if ($this->config) {
                ConfigModel::update([
                    'id' => $this->config->id,
                    'value' => $type,
                ]);
            } else {
                ConfigModel::create([
                    'name' => 'ranking_setting',
                    'value' => $type,
                    'content' => ''
                ]);
            }

            $this->success('保存成功');

        }

        return $this->view->fetch();
    }

    public function show()
    {
        $this->layout = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        $school_id = $this->auth->school_id;

        if ($this->config) {
            $type = $this->config->value;
        } else {
            $type = 1;
        }

        if ($type != 7) {
            $date = get_time($type);
        } else {
            $semster = Semester::where('school_id', $school_id)
                ->where('start_date', '<=', datetime(time(), 'Y-m-d'))
                ->where('end_date', '>=', datetime(time(), 'Y-m-d'))
                ->find();

            if (!$semster) {
                $error = '请先设置学期';
                $this->assign('error', $error);
                return $this->view->fetch();
            } else {
                $date['start_time'] = strtotime($semster->start_date . ' 00:00:00');
                $date['end_time'] = time();
            }
        }

        $offset = 0;
        $limit = 100;
        $data['student'] = [];
        $data['classes'] = [];
        $data['dorm'] = [];

        // 学生榜
        $list = $this->model
            ->alias('record')
            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'record.id = detail.record_id')
            ->where('record.school_id', $school_id)
            ->where('record.created_at', '>=', $date['start_time'])
            ->where('record.created_at', '<=', $date['end_time'])
            ->where('detail.student_id', '>', 0)
            ->whereIn('detail.behavior_category_type', [BehaviorCategory::STUDENT, BehaviorCategory::DORM_STUDENT])
            ->field('detail.student_id,sum(detail.score) score,json_data')
            ->group('detail.student_id')
            ->limit($offset, $limit)
            ->orderRaw('CONVERT(SUM(detail.score),DECIMAL(10,2)) desc')
            ->select();

        if ($list) {
            $list = collection($list)->toArray();

            $student_ids = array_column($list, 'student_id');

            $students = \app\common\model\Student::alias('student')
                ->join('__CLASSES__ classes', 'classes.id = student.class_id')
                ->join('__GRADE__ grade', 'grade.id = student.grade_id')
                ->join('__SCHOOL__ school', 'school.id = student.school_id')
                ->whereIn('student.id', $student_ids)
                ->column('student.id,student.number,student.name,student.gender,student.avatar,school.name school_name,grade.name grade_name,classes.name class_name', 'student.id');

            if ($students) {
                foreach ($students as $key => $value) {
                    $students[$key]['gender_text'] = User::getGender($value['gender']);
                    $students[$key]['avatar'] = $value['avatar'];
                }
            }

            $max_score = current($list)['score'];
            $record_count = $this->model
                ->alias('record')
                ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'record.id = detail.record_id')
                ->where('record.school_id', $school_id)
                ->where('record.created_at', '>=', $date['start_time'])
                ->where('record.created_at', '<=', $date['end_time'])
                ->where('detail.student_id', '>', 0)
                ->whereIn('detail.behavior_category_type', [BehaviorCategory::STUDENT, BehaviorCategory::DORM_STUDENT])
                ->group('detail.student_id')
                ->having('sum(detail.score) > ' . $max_score)
                ->count();

            // 当前分数最大的人 的排名
            $sort = 1;
            if ($record_count) $sort = $record_count + 1;
            foreach ($list as $key => $value) {
                if (isset($students[$value['student_id']])) {
                    $list[$key]['school_name'] = $students[$value['student_id']]['school_name'];
                    $list[$key]['grade_name'] = $students[$value['student_id']]['grade_name'];
                    $list[$key]['class_name'] = $students[$value['student_id']]['class_name'];
                    $list[$key]['name'] = $students[$value['student_id']]['name'];
                    $list[$key]['gender_text'] = $students[$value['student_id']]['gender_text'];
                    $list[$key]['avatar'] = $students[$value['student_id']]['avatar'];
                }  else if ($value['json_data']) {
                    $list[$key]['school_name'] = @$value['json_data']['school_name'];
                    $list[$key]['class_name'] = @$value['json_data']['class_name'];
                    $list[$key]['name'] = @$value['json_data']['student_name'];
                    $list[$key]['avatar'] = @$value['json_data']['avatar'];
                } else {
                    $list[$key]['school_name'] = '';
                    $list[$key]['class_name'] = '';
                    $list[$key]['name'] = '';
                    $list[$key]['gender_text'] = '';
                    $list[$key]['avatar'] = '';
                }
                //数组中第一个是当前分数最高的 排名为$sort
                if ($key == 0) {
                    $list[$key]['sort'] = $sort;
                } else {
                    // 继续循环
                    // 如果当前的分数与上一个的相等 那么就与上一个的排名并列
                    if ($list[$key - 1]['score'] == $value['score']) {
                        $list[$key]['sort'] = $list[$key - 1]['sort'];
                    } else {
                        // 如果不等 那就看看有没有分页情况
                        // 如果有分页 也就是说之前的所有的分数都大于当前的分数 排名累加上
                        $page_count = 0;
                        if ($offset > 0) $page_count = ($offset / $limit) * $limit - 1; // $sort已经叠加过了 所以这里 -1
                        $list[$key]['sort'] = $page_count + $sort;
                    }
                }
                $sort++;
            }

            $data['student'] = $list;
        }

        // 班级榜
        $list = $this->model
            ->alias('record')
            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'record.id = detail.record_id')
            ->where('record.school_id', $school_id)
            ->where('record.created_at', '>=', $date['start_time'])
            ->where('record.created_at', '<=', $date['end_time'])
            ->whereIn('detail.behavior_category_type', [BehaviorCategory::CLASSES])
            ->field('record.class_id,sum(detail.score) score,json_data')
            ->group('record.class_id')
            ->orderRaw('CONVERT(SUM(detail.score),DECIMAL(10,2)) desc')
            ->limit($offset, $limit)
            ->select();
        if ($list) {

            $list = collection($list)->toArray();

            $class_ids = array_column($list, 'class_id');
            $classes = \app\common\model\Classes::alias('classes')
                ->join('__SCHOOL__ school', 'school.id = classes.school_id')
                ->join('__GRADE__ grade', 'grade.id = classes.grade_id')
                ->join('__TEACHER__ teacher', 'teacher.id = classes.headmaster', 'left')
                ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
                ->whereIn('classes.id', $class_ids)
                ->column('classes.id,classes.name,classes.logo,classes.grade_id,grade.name grade_name,classes.school_id,school.name school_name,classes.headmaster,user.nickname headmaster_name,user.avatar headmaster_avatar', 'classes.id');

            $max_score = current($list)['score'];
            $record_count = $this->model
                ->alias('record')
                ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'record.id = detail.record_id')
                ->where('record.school_id', $school_id)
                ->where('record.created_at', '>=', $date['start_time'])
                ->where('record.created_at', '<=', $date['end_time'])
                ->whereIn('detail.behavior_category_type', [BehaviorCategory::CLASSES])
                ->group('record.class_id')
                ->having('sum(detail.score) > ' . $max_score)
                ->count();

            // 当前分数最大的人 的排名
            $sort = 1;
            if ($record_count) $sort = $record_count + 1;
            foreach ($list as $key => $value) {

                if (isset($classes[$value['class_id']])) {
                    $list[$key]['school_name'] = $classes[$value['class_id']]['school_name'];
                    $list[$key]['grade_name'] = $classes[$value['class_id']]['grade_name'];
                    $list[$key]['class_name'] = $classes[$value['class_id']]['name'];
                    $list[$key]['class_logo'] = $classes[$value['class_id']]['logo'];
                    $list[$key]['headmaster_name'] = $classes[$value['class_id']]['headmaster_name'];
                }

                //数组中第一个是当前分数最高的 排名为$sort
                if ($key == 0) {
                    $list[$key]['sort'] = $sort;
                } else {
                    // 继续循环
                    // 如果当前的分数与上一个的相等 那么就与上一个的排名并列
                    if ($list[$key - 1]['score'] == $value['score']) {
                        $list[$key]['sort'] = $list[$key - 1]['sort'];
                    } else {
                        // 如果不等 那就看看有没有分页情况
                        // 如果有分页 也就是说之前的所有的分数都大于当前的分数 排名累加上
                        $page_count = 0;
                        if ($offset > 0) $page_count = ($offset / $limit) * $limit - 1; // $sort已经叠加过了 所以这里 -1
                        $list[$key]['sort'] = $page_count + $sort;
                    }
                }
                $sort++;
            }

            $data['classes'] = $list;
        }


        // 宿舍榜
        $list = $this->model
            ->alias('record')
            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'record.id = detail.record_id')
            ->where('record.school_id', $school_id)
            ->where('record.created_at', '>=', $date['start_time'])
            ->where('record.created_at', '<=', $date['end_time'])
            ->whereIn('detail.behavior_category_type', [BehaviorCategory::DORM])
            ->field('record.dorm_id,record.json_data,sum(detail.score) score')
            ->group('record.dorm_id')
            ->orderRaw('CONVERT(SUM(detail.score),DECIMAL(10,2)) desc')
            ->limit($offset, $limit)
            ->select();

        if ($list) {
            $list = collection($list)->toArray();

            $dorm_ids = array_column($list, 'dorm_id');
            $dorms = Dorm::whereIn('id', $dorm_ids)
                ->column('id,num,number,floor,bed_count,bed_used_count', 'id');

            $max_score = current($list)['score'];
            $record_count = $this->model
                ->alias('record')
                ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'record.id = detail.record_id')
                ->where('record.school_id', $school_id)
                ->where('record.created_at', '>=', $date['start_time'])
                ->where('record.created_at', '<=', $date['end_time'])
                ->whereIn('detail.behavior_category_type', [BehaviorCategory::DORM])
                ->group('record.dorm_id')
                ->having('sum(detail.score) > ' . $max_score)
                ->count();
            // 当前分数最大的人 的排名
            $sort = 1;
            if ($record_count) $sort = $record_count + 1;
            foreach ($list as $key => $value) {
                if ($value['json_data']) {
                    $list[$key]['school_name'] = @$value['json_data']['school_name'];
                    $list[$key]['garden_name'] = $value['json_data']['garden_name'];
                    $list[$key]['building_name'] = $value['json_data']['building_name'];
                    $list[$key]['dorm_number'] = $value['json_data']['dorm_number'];
                }

                $bed_count = \app\common\model\Bed::where('school_id', $value['json_data']['school_id'])
                    ->where('garden_number', $value['json_data']['garden_number'])
                    ->where('building_number',  $value['json_data']['building_number'])
                    ->where('dorm_number', $value['json_data']['dorm_number'])
                    ->where('status', \app\common\model\Bed::ZAIYONG)
                    ->count();
                $list[$key]['bed_used_count'] = $bed_count;

                if (isset($dorms[$value['dorm_id']])) {
                    $list[$key]['bed_count'] = $dorms[$value['dorm_id']]['bed_count'];
                }
                //数组中第一个是当前分数最高的 排名为$sort
                if ($key == 0) {
                    $list[$key]['sort'] = $sort;
                } else {
                    // 继续循环
                    // 如果当前的分数与上一个的相等 那么就与上一个的排名并列
                    if ($list[$key - 1]['score'] == $value['score']) {
                        $list[$key]['sort'] = $list[$key - 1]['sort'];
                    } else {
                        // 如果不等 那就看看有没有分页情况
                        // 如果有分页 也就是说之前的所有的分数都大于当前的分数 排名累加上
                        $page_count = 0;
                        if ($offset > 0) $page_count = ($offset / $limit) * $limit - 1; // $sort已经叠加过了 所以这里 -1
                        $list[$key]['sort'] = $page_count + $sort;
                    }
                }
                $sort++;
            }

            $data['dorm'] = $list;
        }

//        dd($data);

        $this->assign('data', $data);

        return $this->view->fetch();
    }
}
